package com.lechuang.system.manager.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.lechuang.system.entity.RegionDictionary;
import com.lechuang.system.manager.RegionDictionaryManager;
import com.lechuang.system.service.RegionDictionaryService;
import com.lechuang.system.vo.RegionVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class RegionDictionaryManagerImpl implements RegionDictionaryManager {

    /**
     * 顶级节点id
     **/
    public static final Long PRIMARY_NODE_ID = 0L;
    @Resource
    private RegionDictionaryService regionDictionaryService;
    @Override
    public List<RegionVo> getTree(Long id) {

        List<RegionVo>  regionVoList = new ArrayList<>();
        List<RegionDictionary>   regionDictionaries = regionDictionaryService.getTree(id);
        List<RegionVo> finalRegionVoList = regionVoList;
        regionDictionaries.forEach(bean->{
            RegionVo regionVo =new RegionVo()
                    .setId(bean.getId())
                    .setName(bean.getName())
                    .setParentId(bean.getParentId())
                    .setLevel(bean.getLevel());
            finalRegionVoList.add(regionVo);
        });
        if (CollectionUtil.isNotEmpty(finalRegionVoList)){
            regionVoList = buildTree(finalRegionVoList);
        }
        return regionVoList;
    }

    private List<RegionVo> buildTree(List<RegionVo> regionVoList) {
        List<RegionVo> treeList = new LinkedList<>();
        for (RegionVo regionVo : regionVoList) {
            // 判断是否为顶级节点，从顶级节点开始递归
            if (PRIMARY_NODE_ID.equals(regionVo.getParentId())) {
                treeList.add(addChildren(regionVo, regionVoList));
            }
        }
        return treeList;
    }


    private RegionVo addChildren(RegionVo parentTree, List<RegionVo> list) {
        List<RegionVo> childList = new ArrayList<>();
        parentTree.setChildren(childList);
        // 为每一个父节点增加子树（List形式，没有则为空的list）
        for (RegionVo regionVo : list) {
            // 如果不是这个节点的子节点，则跳出递归，继续执行循环
            if (regionVo.getParentId().equals(parentTree.getId())) {
                childList.add(regionVo);
                addChildren(regionVo, list);
            }
        }
        return parentTree;
    }
}
